package com.smzd.ccms.actions;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smzd.ccms.business.ChannelConfigService;
import com.smzd.ccms.business.ChannelService;
import com.smzd.ccms.business.SiteChannelConfigService;
import com.smzd.ccms.business.SiteService;
import com.smzd.ccms.business.SysDictService;
import com.smzd.ccms.core.AbstractSiteResourceController;
import com.smzd.ccms.domain.Channel;
import com.smzd.ccms.domain.ChannelConfig;
import com.smzd.ccms.domain.Site;
import com.smzd.ccms.domain.SiteChannelConfig;
import com.smzd.ccms.domain.SysDict;
import com.smzd.framework.annotation.Access;
import com.smzd.framework.core.business.IFGService;
import com.smzd.framework.system.domain.Meeting;
import com.smzd.framework.utils.JsonHelper;
import com.smzd.framework.utils.MeetingSessionHolder;
import com.smzd.framework.utils.db.ORPage;

@Controller
@RequestMapping("/a/{site}/channels")
@Access("TAG_ROLE_CCMS")
public class ChannelController extends AbstractSiteResourceController<Channel> {
	@Autowired
	private ChannelService service;
	@Autowired
	private SysDictService dictService;
	@Autowired
	private SiteService siteService;
	@Autowired
	private ChannelService channelService;
	@Autowired
	private ChannelConfigService chCfgService;
	@Autowired
	private SiteChannelConfigService sccService;

	@Override
	protected IFGService<Channel> getService() {
		return service;
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	@Override
	public String toAddPage(Map<String, Object> model, @PathVariable("site") String siteStr, Channel elem,
			BindingResult result) throws Exception {
		return super.toAddPage(model, siteStr, elem, result);
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	@Override
	public String postAddData(Map<String, Object> model, @PathVariable("site") String siteStr, Channel elem,
			BindingResult result) throws Exception {
		if (elem.getParent() != null && elem.getParent().getId() == 0) {
			elem.setParent(null);
		}
		elem.setUser(MeetingSessionHolder.getLoginUser());
		String json = null;
		if (elem.getTempchid() > 0) {
			Channel tempch = service.getItemById(elem.getTempchid());
			if (tempch != null) {
				elem.setType(tempch.getType());//这个很关键，能复制，必须类型是一样的。
				json = super.postAddData(model, siteStr, elem, result);
				try {
					chCfgService.duplicateChannelConfigs(elem, tempch);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		if (json == null) {
			json = super.postAddData(model, siteStr, elem, result);
		}
		return json;
	}

	/**
	 * 为已经存在的栏目配置所有的视角、模块、参数等。用指定的栏目作为模板。
	 * 
	 * @param model
	 * @param siteStr
	 * @param elem 只需要填充里面的id和tempchid就行了。
	 * @param result
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/copytemplet", method = RequestMethod.POST)
	@ResponseBody
	public String postcopytemplet(Map<String, Object> model, @PathVariable("site") String siteStr, Channel elem,
	        BindingResult result) throws Exception {
		// 要配置的目标栏目
		Channel origin = service.getItemById(elem.getId());
		// 要拷贝的模板栏目
		Channel tempch = service.getItemById(elem.getTempchid());
		try {
			// 再执行之前必须：1. 同步两个栏目的类型，2. 把原先的栏目视角配置删除掉。然后可以继续拷贝
			origin.setType(tempch.getType());
			service.updateChannelType(origin);
			service.removeChannelConfigs(origin);
			chCfgService.duplicateChannelConfigs(origin, tempch);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JsonHelper.getSuccessJsonString();
	}

	@RequestMapping(value = { "/index.html", "" }, method = RequestMethod.GET)
	@Override
	public String toListPage(Map<String, Object> model, @PathVariable("site") String siteStr, Channel elem,
			BindingResult result) throws Exception {
		return super.toListPage(model, siteStr, elem, result);
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	@Override
	public String getListData(Map<String, Object> model, @PathVariable("site") String siteStr,
			ORPage<Meeting, Channel> page, BindingResult result) throws Exception {
		return super.getListData(model, siteStr, page, result);
	}

	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	@Override
	public String toEditPage(Map<String, Object> model, @PathVariable("site") String siteStr, Channel elem,
			BindingResult result) throws Exception {
		Site site = setCurrentSite(model, siteStr);
		elem = service.getItemById(elem.getId());
		if (elem != null) {
			if (site.getOwner().getId() - elem.getOwner().getId() == 0) {
				return super.toEditPage(model, elem, result);
			}
		}
		throw new Exception("unexpected id=" + elem.getId());
	}

	@RequestMapping(value = { "/{channel}/index.html", "/{channel}" }, method = RequestMethod.GET)
	public String toEditViewPage(Map<String, Object> model, @PathVariable("site") String siteStr,
			@PathVariable("channel") String channelStr) throws Exception {
		Site site = setCurrentSite(model, siteStr);
		Channel channel = site.getChannel(channelStr);
		if (channel != null) {
			model.put("item", channel);
			model.put("_channel_", channelStr);
			return getMyView("ch-index.ftl");
		}
		throw new Exception("栏目不存在！");
	}
	@RequestMapping(value = { "/outer-{chId}/index.html"}, method = RequestMethod.GET)
	public String toEditOuterViewPage(Map<String, Object> model, @PathVariable("site") String siteStr,
			@PathVariable("chId") Integer chId) throws Exception {
		Site site = setCurrentSite(model, siteStr);
		Channel channel = site.getChannel(chId);
		if (channel != null) {
			model.put("item", channel);
			model.put("_channel_", "outer-"+channel.getId());
			return getMyView("ch-index.ftl");
		}
		throw new Exception("栏目不存在！");
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	@ResponseBody
	@Override
	public String postEditData(Map<String, Object> model, @PathVariable("site") String siteStr, Channel elem,
			BindingResult result) throws Exception {
		if (elem.getParent().getId() == 0) {
			elem.setParent(null);
		}
		return super.postEditData(model, siteStr, elem, result);
	}

	@RequestMapping(value = "/remove", method = RequestMethod.POST)
	@ResponseBody
	@Override
	public String postRemoveData(Map<String, Object> model, @PathVariable("site") String siteStr, Channel elem,
			BindingResult result) throws Exception {
		return super.postRemoveData(model, siteStr, elem, result);
	}

	/**
	 * 为指定频道栏目展示各个视角的模板配置。<br>
	 * 所谓视角，是指由于不同的频道栏目类型而具有的不同的模板配置项，如前台列表模板、后台详情模板等。<br>
	 * 这些模板配置项是由模型决定的，存在与数据库中的，该配置只能手动修改。<br>
	 * 如何定义视角与模板是这个问题的重中之重。
	 * 
	 * @param channelStr
	 *            频道ID
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/{channel}/templatecfgs/index.html")
	public String toChannelTemplateConfigsIndexPage(Map<String, Object> model, @PathVariable("site") String siteStr,
			@PathVariable("channel") String channelStr) throws Exception {
		Site site = translateSite(siteStr);
		if (site == null) {
			site = siteService.getSiteByPath(siteStr);
		}
		if (site == null) {
			throw new Exception("站点不存在！");
		}
		Channel channel = site.getChannel(channelStr);
		if (channel == null) {
			channel = channelService.getChannelByPath(siteStr, channelStr);
		}
		if (channel == null || channel.getOwner().getId() - site.getOwner().getId() != 0) {
			throw new Exception("站点不存在！");
		}
		model.put("_site", site);
		model.put("_channel", channel);
		model.put("_site_", siteStr);
		model.put("_channel_", channelStr);

		SysDict dict = dictService.getChCfgSysDictByChannelType(channel.getType());
		List<SysDict> dicts = dictService.getSysDictsForChCfgs(channel.getId(), dict.getValue());

		model.put("_dicts", dicts);

		return getMyView("templatecfgs.ftl");
	}
	@RequestMapping("/outer-{chId}/templatecfgs/index.html")
	public String toOuterChannelTemplateConfigsIndexPage(Map<String, Object> model, @PathVariable("site") String siteStr,
			@PathVariable("chId") Integer chId) throws Exception {
		Site site = translateSite(siteStr);
		if (site == null) {
			site = siteService.getSiteByPath(siteStr);
		}
		if (site == null) {
			throw new Exception("站点不存在！");
		}
		Channel channel = site.getChannel(chId);
		if (channel == null) {
			channel = channelService.getChannelByPathId(siteStr, chId);
		}
		if (channel == null || channel.getOwner().getId() - site.getOwner().getId() != 0) {
			throw new Exception("站点不存在！");
		}
		model.put("_site", site);
		model.put("_channel", channel);
		model.put("_site_", siteStr);
		model.put("_channel_", "outer-"+channel.getId());

		SysDict dict = dictService.getChCfgSysDictByChannelType(channel.getType());
		List<SysDict> dicts = dictService.getSysDictsForChCfgs(channel.getId(), dict.getValue());

		model.put("_dicts", dicts);

		return getMyView("templatecfgs.ftl");
	}

	@RequestMapping("/{channel}/templatecfgs/edit.do")
	@ResponseBody
	public String updateChannelConfigs(@PathVariable("site") String siteStr,
			@PathVariable("channel") String channelStr, @RequestParam("dictid") int[] dictids,
			@RequestParam("tmplid") int[] tmplids, @RequestParam("path") String[] paths) throws Exception {
		Site site = translateSite(siteStr);
		if (site == null) {
			site = siteService.getSiteByPath(siteStr);
		}
		if (site == null) {
			throw new Exception("站点不存在！");
		}
		Channel channel = site.getChannel(channelStr);
		if (channel == null) {
			channel = channelService.getChannelByPath(siteStr, channelStr);
		}
		if (channel == null || channel.getOwner().getId() - site.getOwner().getId() != 0) {
			throw new Exception("栏目不存在！");
		}
		chCfgService.updateChannelConfigs(channel, dictids, tmplids, paths);
		return JsonHelper.getSuccessJsonString();
	}
	@RequestMapping("/outer-{chId}/templatecfgs/edit.do")
	@ResponseBody
	public String updateOuterChannelConfigs(@PathVariable("site") String siteStr,
			@PathVariable("chId") Integer chId, @RequestParam("dictid") int[] dictids,
			@RequestParam("tmplid") int[] tmplids, @RequestParam("path") String[] paths) throws Exception {
		Site site = translateSite(siteStr);
		if (site == null) {
			site = siteService.getSiteByPath(siteStr);
		}
		if (site == null) {
			throw new Exception("站点不存在！");
		}
		Channel channel = site.getChannel(chId);
		if (channel == null) {
			channel = channelService.getChannelByPathId(siteStr, chId);
		}
		if (channel == null || channel.getOwner().getId() - site.getOwner().getId() != 0) {
			throw new Exception("栏目不存在！");
		}
		chCfgService.updateChannelConfigs(channel, dictids, tmplids, paths);
		return JsonHelper.getSuccessJsonString();
	}

	/**
	 * 为指定频道展示一个特定的视角的模板配置。<br>
	 * 这个页面其实重点在于展示该视角下模板配置的其他配置内容，比如小组件配置等。<br>
	 * 修改这个视角的模板配置在上面的这个页面中进行就行了。
	 * 
	 * @param chId
	 * @param cfgId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/{channel}/templatecfgs/{cfgId}/index.html")
	public String toChannelTemplateConfigIndexPage(Map<String, Object> model, @PathVariable("site") String siteStr,
			@PathVariable("channel") String channelStr, @PathVariable("cfgId") int cfgId) throws Exception {
		Site site = translateSite(siteStr);
		if (site == null) {
			throw new Exception("站点不存在！");
		}
		Channel channel = site.getChannel(channelStr);
		if (channel == null || channel.getOwner().getId() - site.getOwner().getId() != 0) {
			throw new Exception("栏目不存在！");
		}
		ChannelConfig cfg = chCfgService.getItemById(cfgId);
		if (cfg.getScope().getId() - channel.getId() != 0) {
			throw new Exception("该视角配置不属于当前栏目！");
		}

		model.put("_site", site);
		model.put("_channel", channel);
		model.put("_chcfg", cfg);
		return getMyView("templatecfg.ftl");
	}
	@RequestMapping("/outer-{chId}/templatecfgs/{cfgId}/index.html")
	public String toOuterChannelTemplateConfigIndexPage(Map<String, Object> model, @PathVariable("site") String siteStr,
			@PathVariable("chId") Integer chId, @PathVariable("cfgId") int cfgId) throws Exception {
		Site site = translateSite(siteStr);
		if (site == null) {
			throw new Exception("站点不存在！");
		}
		Channel channel = site.getChannel(chId);
		if (channel == null || channel.getOwner().getId() - site.getOwner().getId() != 0) {
			throw new Exception("栏目不存在！");
		}
		ChannelConfig cfg = chCfgService.getItemById(cfgId);
		if (cfg.getScope().getId() - channel.getId() != 0) {
			throw new Exception("该视角配置不属于当前栏目！");
		}

		model.put("_site", site);
		model.put("_channel", channel);
		model.put("_chcfg", cfg);
		return getMyView("templatecfg.ftl");
	}

	/**
	 * 把这个栏目设置为或取消作为样板栏目。<br>
	 * 样板栏目是用来选择作为设置<b>新</b>栏目的栏目配置的样板的。其type、视角模板配置（含模板选择）、小组件配置（含小组件的参数配置）
	 * 等都会拷贝过来，之后只需要修改必要的参数配置即可。
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/toggleastemplate")
	@ResponseBody
	public String toggleAsTemplate(Map<String, Object> model, @PathVariable("site") String siteStr,
			@RequestParam("id") int chId) {
		Site site = translateSite(siteStr);
		SiteChannelConfig scc = sccService.getSiteChannelConfig(site.getOwner().getId(),
				SysDict.ID_SITE_CH_CONFIG_TEMPLATE, chId);
		if (scc != null) {
			sccService.toggleDisabled(scc);
		} else {
			scc = new SiteChannelConfig();
			scc.setOwner(site.getOwner());
			scc.setSysDict(new SysDict(SysDict.ID_SITE_CH_CONFIG_TEMPLATE));
			scc.setChannel(new Channel(chId));
			scc.setName("site" + site.getId() + "-dictid" + SysDict.ID_SITE_CH_CONFIG_TEMPLATE);
			sccService.insert(scc);
		}
		return JsonHelper.getSuccessJsonString();
	}

	@RequestMapping("/templatechannels")
	@ResponseBody
	public String getTemplateChannels(@PathVariable("site") String siteStr) {
		Site site = translateSite(siteStr);
		return service.getTemplateChannels(site.getOwner());
	}

	@RequestMapping("/position.do")
	@ResponseBody
	public String changeChannelPositionForSite(@PathVariable("site") String siteStr, int id, int parentid,
			double sequence) {
		Site site = translateSite(siteStr);
		Channel ch = service.getItemById(id);
		if (ch == null || ch.getOwner().getId().intValue() != site.getOwner().getId().intValue()) {
			return JsonHelper.getFailJsonString("目标栏目不属于当前站点！");
		}
		if (parentid > 0) {
			Channel parent = service.getItemById(parentid);
			if (parent == null || parent.getOwner().getId().intValue() != site.getOwner().getId().intValue()) {
				return JsonHelper.getFailJsonString("父栏目不属于当前站点！");
			}
			ch.setParent(parent);
		} else {
			ch.setParent(null);
		}
		ch.setSequence(sequence);
		service.updateChannelPosition(ch);
		return JsonHelper.getSuccessJsonString();
	}

	@RequestMapping("/resetpos.do")
	@ResponseBody
	public String resetChannelPositionsForChannel(@PathVariable("site") String siteStr) {
		Site site = translateSite(siteStr);
		if (site == null) {
			return JsonHelper.getFailJsonString();
		}
		service.resetChannelPositionsForSite(site);
		return JsonHelper.getSuccessJsonString();
	}
	
	/**
	 * 编辑论坛公告页面
	 * @param model
	 * @param siteStr
	 * @param elem
	 * @param result
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value = "/editNotice", method = RequestMethod.GET)
    public String toEditNoticePage(Map<String, Object> model, @PathVariable("site") String siteStr,
            Channel elem, BindingResult result) throws Exception {
    	elem = service.getItemById(elem.getId());
		if(elem!=null){
	    	model.put("item", elem);
			model.put("_site_", siteStr);

	        return getMyView("edit-notice.ftl");
		}

        throw new Exception("栏目不存在！");
    }
    
    /**
     * 提交论坛公告
     * @param model
     * @param siteStr
     * @param channelStr
     * @param elem
     * @param result
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/editNotice", method = RequestMethod.POST)
    @ResponseBody
    public String postEditNoticeData(Map<String, Object> model, @PathVariable("site") String siteStr,
            Channel elem, BindingResult result) throws Exception {
    	Channel channel = service.getItemById(elem.getId());
    	channel.setNotice(elem.getNotice());
		return super.postEditData(model, siteStr, channel, result);
    }
}